package com.library.filter;

import com.library.dao.StudentDao;
import com.library.entity.Student;
import com.library.util.StudentContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 学生端过滤器
 */
@WebFilter("/student/*")
public class StudentFilter implements Filter {

    private final StudentDao studentDao = new StudentDao();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        if (session == null) {
            // 未登录
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        Student student = (Student) session.getAttribute("student");

        if (student == null) {
            // 未登录
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        Student studentInfo = studentDao.getBySno(student.getSno());

        if (studentInfo == null || !studentInfo.getPassword().equals(student.getPassword())) {
            // 用户信息有误
            session.invalidate();
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        StudentContext.setStudent(student);
        filterChain.doFilter(request, response);
        StudentContext.removeStudent();
    }

    @Override
    public void destroy() {

    }
}
